package com.example.taobaounion.utils;

import android.content.Context;
import android.content.SharedPreferences;

import com.example.taobaounion.base.BaseApplication;
import com.example.taobaounion.model.domain.CacheWithDuration;
import com.google.gson.Gson;

public class JsonCacheUtil {
    private static final JsonCacheUtil ourInstance = new JsonCacheUtil();

    private final static String json_cache_name = "json_cache_sp_name";
    private final SharedPreferences mSharedPreferences;
    private final Gson mGson;

    public static JsonCacheUtil getInstance() {
        return ourInstance;
    }

    private JsonCacheUtil() {
        mGson = new Gson();
        mSharedPreferences = BaseApplication.getAppContext().getSharedPreferences(json_cache_name, Context.MODE_PRIVATE);
    }

    private void saveCache(String key, Object value, long duration) {
        SharedPreferences.Editor edit = mSharedPreferences.edit();

        String valueStr = mGson.toJson(value);

        if (duration != -1L) {
            duration += System.currentTimeMillis();
        }

        CacheWithDuration cacheWithDuration = new CacheWithDuration(duration, valueStr);

        String cacheWithTime = mGson.toJson(cacheWithDuration);

        edit.putString(key, cacheWithTime);

        edit.apply();
    }

    public void saveCache(String key, Object value) {
        saveCache(key, value, -1L);
    }

    public void delCache(String key) {
        mSharedPreferences.edit().remove(key).apply();
    }

    public <T> T getValue(String key, Class<T> clazz) {
        String valueWithDuration = mSharedPreferences.getString(key, null);

        if (valueWithDuration == null) {
            return null;
        }

        CacheWithDuration cacheWithDuration = mGson.fromJson(valueWithDuration, CacheWithDuration.class);

        long duration = cacheWithDuration.getDuration();

        if (duration != -1 && duration - System.currentTimeMillis() <= 0) {
            return null;
        } else {
            String cache = cacheWithDuration.getCache();

            return mGson.fromJson(cache, clazz);
        }
    }
}